﻿using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Quartz;

namespace PmSoft.Quartz;

public class QuartzJobRunner : IJob
{
    private readonly IServiceProvider serviceProvider;
    private readonly ILogger logger;
    public QuartzJobRunner(IServiceProvider serviceProvider, ILogger<QuartzJobRunner> logger)
    {
        this.serviceProvider = serviceProvider;
        this.logger = logger;
    }


    public async Task Execute(IJobExecutionContext context)
    {
        using (var scope = serviceProvider.CreateScope())
        {
            var jobType = context.JobDetail.JobType;
            var job = scope.ServiceProvider.GetRequiredService(jobType) as IJob;
            await job.Execute(context).ContinueWith(t =>
            {
                t.Exception?.Handle(exception =>
                {
                    logger.LogError(exception, "Execute job exception.");
                    return true;
                });
            });
        }
    }
}
